var authCodeApi = {
    "AliPay": "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=APPID&scope=SCOPE&redirect_uri=REDIRECT_URI&state=STATE",
    "WeChat": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect",
}
let setParam = (url, param) => {
    Object.keys(param).forEach(key => {
        url = url.replace(key, param[key])
    })
    return url;
}
let genAuthUrl = (type, param) => {
    if (authCodeApi[type]) {
        return setParam(authCodeApi[type], param);
    } else {
        console.error("错误类型:" + type);
        return window.location.href;
    }
}
var OAuthParam = {
    "AliPay": {
        APPID: "2021002124692648",
        REDIRECT_URI: "http://lhhcherry.gitee.io/ssmell/ourrecord/dist/",
        //REDIRECT_URI: "https://wxtest.beeb.com.cn/SitMerAppManager/devtest/",
        SCOPE: "auth_base",
        STATE: "SSMELL_OURSPACE",
        SCOPE_PREFIX: "auth_",
    },
    "WeChat": {
        APPID: "wxa6558ffe7a73f1b5",
        REDIRECT_URI: "http://lhhcherry.gitee.io/ssmell/ourrecord/dist/",
        //REDIRECT_URI: "http://10.7.25.44:8000/",
        SCOPE: "snsapi_base",
        STATE: "SSMELL_OURSPACE",
        SCOPE_PREFIX: "snsapi_",
    }
}
let genAuthParam = (type) => {
    let param = OAuthParam[type];
    if (param) {
        let encodeRedirectUrl = window.encodeURIComponent(param.REDIRECT_URI);
        param.SCOPE = param.SCOPE_PREFIX + "userinfo";
        return param;
    } else {
        throw Error("不支持的OAuth类型:", type);
    }
}
export let executeOAuth2 = function(type, state) {
    console.log("execute Oauth2:", type)
    // TODO 添加平台自动识别代码。
    let authParam = genAuthParam(type);
    let dealedApi = genAuthUrl(type, authParam)
    window.location.replace(dealedApi);
}

function getSearchObject() {
    let searchStr = window.location.search;
    if (searchStr) {
        let searchObj = {};
        let searchArr = searchStr.substr(1).split("&")
        searchArr.forEach(searchItem => {
            let searchItemArr = searchItem.split("=")
            if (searchItemArr.length !== 2) {
                console.error("获取参数异常")
                return;
            }
            searchObj[searchItemArr[0]] = searchItemArr[1]
        })
        return searchObj;
    }
    return false;
}
export let OAuthCallback = function(callback, option) {
    window.addEventListener("load", () => {
        let searchObj = getSearchObject();
        if (searchObj === false || !searchObj.state) {
            executeOAuth2(option.type);
        } else {
            callback(searchObj);
        }
    })
}